package com.loveofsoftware.fotolab.effects;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;

public class SketchInitialEffect implements InitialEffects {

	public Bitmap transform(Bitmap in) {
		int [] pixels = new int[in.getWidth() * in.getHeight()];
		
		in = in.copy(Config.ARGB_8888, true);
		in.getPixels(pixels, 0, in.getWidth(), 0, 0, in
				.getWidth(), in.getHeight());
		for (int i = 0; i < pixels.length; i++) {
			int p = pixels[i];
			int r = p & 0x00FF0000 >> 16;
        	int g = p & 0x0000FF >> 8;
        	int b = p & 0x000000FF;
        	pixels[i] = (int) ( ( r + g + b ) / 40.0 );

		}
		
		int convolutionSize = 3;
		int w = in.getWidth();
		int h = in.getHeight();

		int[][] convolution = { { 0, -1, 0 }, { -1, 4, -1 }, { 0, -1, 0 } };

		int[] newImage = new int[pixels.length];
		// Apply the convolution to the whole image, note that we start at
		// 1 instead 0 zero to avoid out-of-bounds access
		for (int y = 1; y + 1 < h; y++) {
			for (int x = 1; x + 1 < w; x++) {
				int idx = (y * w) + x;

				// Apply the convolution
				for (int cy = 0; cy < convolutionSize; cy++) {
					for (int cx = 0; cx < convolutionSize; cx++) {
						int cIdx = (((y - 1) + cy) * w) + ((x - 1) + cx);
						newImage[idx] += convolution[cy][cx] * pixels[cIdx];
					}
				}

				// pixel value rounding
				if (newImage[idx] < 0) {
					newImage[idx] = -newImage[idx];
				} else {
					newImage[idx] = 0;
				}
				if (newImage[idx] > 0) {
					newImage[idx] = 120 - newImage[idx];
				} else {
					newImage[idx] = 255;
				}

			}
		}

		// Convert to "proper" grayscale
		for (int y = 0; y < h; y++) {
			for (int x = 0; x < w; x++) {
				int idx = (y * w) + x;
				int p = newImage[idx];
				newImage[idx] = 0xFF000000 | (p << 16) | (p << 8) | p;
			}
		}
		
		in.setPixels(newImage, 0, in.getWidth(), 0, 0, in.getWidth(), in.getHeight());
		return in;
	}

}
